šŸ Python Control Structures

A Complete Beginner's Guide with Examples

Introduction

Control structures are fundamental building blocks in programming that allow you to control the flow of your program's execution. Instead of executing code line by line from top to bottom, control structures enable you to make decisions, repeat actions, and create more sophisticated program logic.

What are Control Structures?
Control structures are programming constructs that determine the order in which statements are executed in a program. They allow you to:
  • Make decisions based on conditions (if-else)
  • Repeat actions multiple times (loops)
  • Skip or exit from repetitive processes (break, continue)
  • Create complex logical flows in your programs

In this comprehensive tutorial, we'll explore Python's control structures including conditional statements, loops, and loop control statements with detailed explanations and practical examples.

1. Conditional Statements

Definition:
Conditional statements (also called decision-making statements) allow your program to execute different blocks of code based on whether certain conditions evaluate to True or False. They are the foundation of creating intelligent, responsive programs that can make decisions.

Conditional statements evaluate boolean expressions (conditions that result in True or False) and execute specific code blocks accordingly. This is how programs make choices, similar to how humans make decisions in everyday life.

In Python, indentation is crucial! The code block that belongs to a conditional statement must be indented (typically 4 spaces or 1 tab). This is not just for readability - it's a syntax requirement.

1.1 If-Else Statements

The if-else statement is the most basic form of conditional logic. It checks a condition and executes one block of code if the condition is true, and another block if it's false.

# Basic if-else example age = 18 if age >= 18: print("You are an adult") print("You can vote") else: print("You are a minor") print("You cannot vote yet")
You are an adult You can vote
The colon (:) at the end of the if and else lines is mandatory, and the indented block beneath each statement determines which code belongs to that condition.
# Another example with user input temperature = 30 if temperature > 25: print("It's hot outside!") print("Remember to drink water") else: print("The weather is pleasant") print("Enjoy your day")
It's hot outside! Remember to drink water

1.2 If-Elif-Else Statements

When you need to check multiple conditions, you can use elif (short for "else if"). Python evaluates each condition in order from top to bottom and executes the first block where the condition is true. Once a condition is satisfied, Python skips the remaining conditions.

# Grade calculation example score = 85 if score >= 90: grade = "A" print("Excellent work!") elif score >= 80: grade = "B" print("Great job!") elif score >= 70: grade = "C" print("Good effort!") elif score >= 60: grade = "D" print("You passed, but need improvement") else: grade = "F" print("Unfortunately, you failed") print(f"Your grade is: {grade}")
Great job! Your grade is: B
You can have as many elif statements as you need, but only one if and one else per conditional structure. The else is optional - use it when you want a default action if no conditions are met.
# Day of week example day = 3 if day == 1: print("Monday - Start of the work week") elif day == 2: print("Tuesday - Keep going!") elif day == 3: print("Wednesday - Halfway there!") elif day == 4: print("Thursday - Almost Friday!") elif day == 5: print("Friday - TGIF!") elif day == 6: print("Saturday - Weekend!") elif day == 7: print("Sunday - Relax and recharge") else: print("Invalid day number")
Wednesday - Halfway there!

1.3 Nested If Statements

You can place if statements inside other if statements to check multiple conditions at different levels. This is called nesting. Nested conditions are useful when you need to check secondary conditions only after a primary condition is met.

# Login validation example username = "admin" password = "secret123" is_active = True if username == "admin": print("Username is correct") if password == "secret123": print("Password is correct") if is_active: print("Login successful!") print("Welcome to the system") else: print("Account is inactive") print("Please contact support") else: print("Incorrect password") print("Please try again") else: print("Username not found") print("Please check your username")
Username is correct Password is correct Login successful! Welcome to the system
# Age and ticket price example age = 15 is_student = True if age < 18: print("You qualify for youth discount") if is_student: print("Additional student discount applied!") price = 5 else: price = 8 else: if age >= 65: print("Senior citizen discount applied") price = 10 else: price = 15 print(f"Ticket price: ${price}")
You qualify for youth discount Additional student discount applied! Ticket price: $5

1.4 Single-Line If Statements

For simple conditions with a single action, you can write if statements on one line to make your code more concise. However, use this sparingly and only when it improves readability.

# Single-line if statement temperature = 30 if temperature > 25: print("It's hot outside!") # Multiple single-line statements x = 10 if x > 5: print("x is greater than 5") if x < 20: print("x is less than 20") if x == 10: print("x equals 10")
It's hot outside! x is greater than 5 x is less than 20 x equals 10
While single-line if statements are convenient, avoid using them for complex logic or when you need multiple statements. They can make your code harder to read and debug.

1.5 Ternary Operator (Conditional Expression)

The ternary operator is a compact way to write simple if-else statements in a single line. It's especially useful for assigning values conditionally. The syntax is: value_if_true if condition else value_if_false

# Basic ternary operator age = 20 status = "adult" if age >= 18 else "minor" print(f"Status: {status}") # Finding maximum of two numbers a, b = 10, 25 max_value = a if a > b else b print(f"Maximum value: {max_value}") # Minimum of two numbers min_value = a if a < b else b print(f"Minimum value: {min_value}") # Even or odd number = 7 result = "even" if number % 2 == 0 else "odd" print(f"{number} is {result}") # Pass or fail score = 75 result = "Pass" if score >= 50 else "Fail" print(f"Result: {result}")
Status: adult Maximum value: 25 Minimum value: 10 7 is odd Result: Pass
The ternary operator is best used for simple assignments. For complex logic with multiple statements, use regular if-else blocks for better readability.

2. Loops

Definition:
Loops are control structures that allow you to execute a block of code repeatedly. Instead of writing the same code multiple times, loops let you automate repetitive tasks efficiently. Python provides two main types of loops:
  • For loops: Used when you know how many times you want to repeat (iterate over a sequence)
  • While loops: Used when you want to repeat until a condition becomes false

Loops are essential for processing collections of data, performing repetitive calculations, and creating interactive programs. They save time, reduce code duplication, and make programs more maintainable.

Every loop must have a way to terminate (end), otherwise you'll create an infinite loop that runs forever and can crash your program!

2.1 For Loops

For loops are used to iterate over a sequence (like a list, tuple, string, or range). They execute the code block once for each item in the sequence. The loop automatically handles moving from one item to the next.

# Iterating over a list fruits = ["apple", "banana", "cherry", "orange"] print("Fruits in my basket:") for fruit in fruits: print(f"- {fruit}") print("\nI like these fruits:") for fruit in fruits: print(f"I like {fruit}")
Fruits in my basket: - apple - banana - cherry - orange I like these fruits: I like apple I like banana I like cherry I like orange
# Using range() function print("Counting from 1 to 5:") for i in range(1, 6): print(i) print("\nEven numbers from 0 to 10:") for i in range(0, 11, 2): print(i, end=" ") print("\n\nCounting backwards from 10 to 1:") for i in range(10, 0, -1): print(i, end=" ")
Counting from 1 to 5: 1 2 3 4 5 Even numbers from 0 to 10: 0 2 4 6 8 10 Counting backwards from 10 to 1: 10 9 8 7 6 5 4 3 2 1
The range() function generates a sequence of numbers. range(start, stop, step) where start is inclusive, stop is exclusive, and step is the increment. If you omit start, it defaults to 0. If you omit step, it defaults to 1.
# Iterating over a string word = "Python" print("Letters in 'Python':") for letter in word: print(letter, end=" ") print("\n\nCharacter positions:") for letter in word: print(f"{letter} is a character")
Letters in 'Python': P y t h o n Character positions: P is a character y is a character t is a character h is a character o is a character n is a character

2.2 While Loops

While loops continue executing as long as a condition remains true. They're useful when you don't know in advance how many times you need to loop. The condition is checked before each iteration, and if it's false, the loop stops.

# Basic while loop - counting count = 1 print("Counting with while loop:") while count <= 5: print(f"Count is: {count}") count += 1 print("Loop finished!") # Countdown example countdown = 5 print("\nCountdown:") while countdown > 0: print(countdown) countdown -= 1 print("Blast off!")
Counting with while loop: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Loop finished! Countdown: 5 4 3 2 1 Blast off!
Be careful with while loops! If the condition never becomes false, you'll create an infinite loop. Always ensure there's a way for the loop to end by modifying the condition variable inside the loop.
# Sum of numbers total = 0 number = 1 while number <= 10: total += number number += 1 print(f"Sum of numbers 1 to 10: {total}") # Finding first number divisible by 7 num = 50 while num % 7 != 0: num += 1 print(f"First number >= 50 divisible by 7: {num}")
Sum of numbers 1 to 10: 55 First number >= 50 divisible by 7: 56

2.3 Nested Loops

You can place loops inside other loops. The inner loop completes all its iterations for each single iteration of the outer loop. This is useful for working with multi-dimensional data or creating patterns.

# Multiplication table print("Multiplication Table (1-5):") for i in range(1, 6): for j in range(1, 6): product = i * j print(f"{product:3}", end=" ") print() # New line after each row
Multiplication Table (1-5): 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
# Pattern printing - right triangle print("\nRight Triangle Pattern:") for i in range(1, 6): for j in range(i): print("*", end="") print() # Pattern printing - square print("\nSquare Pattern:") for i in range(4): for j in range(4): print("#", end=" ") print()
Right Triangle Pattern: * ** *** **** ***** Square Pattern: # # # # # # # # # # # # # # # #
# Nested loop with lists students = ["Alice", "Bob", "Charlie"] subjects = ["Math", "Science", "English"] print("Student Enrollments:") for student in students: print(f"\n{student} is enrolled in:") for subject in subjects: print(f" - {subject}")
Student Enrollments: Alice is enrolled in: - Math - Science - English Bob is enrolled in: - Math - Science - English Charlie is enrolled in: - Math - Science - English

2.4 Loop Iterations

Understanding how loops iterate is crucial. Each pass through the loop is called an iteration. You can control iterations using the range() function parameters, or track them manually with counters.

# Demonstrating iterations with counter numbers = [10, 20, 30, 40, 50] iteration = 0 print("Processing numbers:") for num in numbers: iteration += 1 print(f"Iteration {iteration}: Processing number {num}") print(f" Double of {num} is {num * 2}") print(f"\nTotal iterations: {iteration}")
Processing numbers: Iteration 1: Processing number 10 Double of 10 is 20 Iteration 2: Processing number 20 Double of 20 is 40 Iteration 3: Processing number 30 Double of 30 is 60 Iteration 4: Processing number 40 Double of 40 is 80 Iteration 5: Processing number 50 Double of 50 is 100 Total iterations: 5
# Using range with different step values print("Every 3rd number from 0 to 20:") for i in range(0, 21, 3): print(i, end=" ") print("\n\nEvery 5th number from 100 to 50 (backwards):") for i in range(100, 45, -5): print(i, end=" ")
Every 3rd number from 0 to 20: 0 3 6 9 12 15 18 Every 5th number from 100 to 50 (backwards): 100 95 90 85 80 75 70 65 60 55 50

2.5 Enumerate and Zip Functions

Python provides powerful built-in functions to enhance loop functionality. Enumerate adds a counter to an iterable, while zip combines multiple iterables element by element.

# Enumerate - adds index to items fruits = ["apple", "banana", "cherry", "orange"] print("Using enumerate (starting from 0):") for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}") # Starting enumerate from 1 instead of 0 print("\nUsing enumerate (starting from 1):") for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")
Using enumerate (starting from 0): Index 0: apple Index 1: banana Index 2: cherry Index 3: orange Using enumerate (starting from 1): 1. apple 2. banana 3. cherry 4. orange
# Zip - combines multiple lists names = ["Alice", "Bob", "Charlie", "Diana"] ages = [25, 30, 35, 28] cities = ["New York", "London", "Paris", "Tokyo"] print("Using zip to combine lists:") for name, age, city in zip(names, ages, cities): print(f"{name} is {age} years old and lives in {city}") # Creating a dictionary from two lists using zip print("\nCreating dictionary with zip:") fruits = ["apple", "banana", "cherry"] prices = [1.50, 0.75, 2.00] fruit_prices = dict(zip(fruits, prices)) print(fruit_prices) for fruit, price in fruit_prices.items(): print(f"{fruit}: ${price}")
Using zip to combine lists: Alice is 25 years old and lives in New York Bob is 30 years old and lives in London Charlie is 35 years old and lives in Paris Diana is 28 years old and lives in Tokyo Creating dictionary with zip: {'apple': 1.5, 'banana': 0.75, 'cherry': 2.0} apple: $1.5 banana: $0.75 cherry: $2.0
When using zip with lists of different lengths, it stops at the shortest list. Use enumerate when you need both the index and value, and use zip when you need to process multiple sequences together.

3. Loop Control Statements

Definition:
Loop control statements change the normal flow of loop execution. They give you fine-grained control over how loops behave, allowing you to:
  • break: Exit the loop immediately
  • continue: Skip the rest of the current iteration and move to the next one
  • pass: Do nothing (placeholder for future code)

These statements are essential for creating efficient loops that can handle special cases, exit early when needed, or skip unwanted iterations.

3.1 Break Statement

The break statement immediately exits the loop, regardless of the loop condition. It's useful when you've found what you're looking for or need to stop based on a certain condition. Once break is executed, the program continues with the code after the loop.

# Finding a specific number numbers = [5, 12, 8, 15, 20, 3, 25] print("Searching for a number greater than 10:") for num in numbers: print(f"Checking {num}...") if num > 10: print(f"Found it! {num} is greater than 10") break print(f"{num} is not greater than 10") print("Search completed!")
Searching for a number greater than 10: Checking 5... 5 is not greater than 10 Checking 12... Found it! 12 is greater than 10 Search completed!
# Finding a character in a string text = "Hello World" search_char = "W" print(f"Searching for '{search_char}' in '{text}':") for index, char in enumerate(text): if char == search_char: print(f"Found '{search_char}' at position {index}") break else: print(f"'{search_char}' not found in the text")
Searching for 'W' in 'Hello World': Found 'W' at position 6
# Login attempts with break print("Login System:") correct_password = "python123" max_attempts = 3 for attempt in range(1, max_attempts + 1): password = input(f"Attempt {attempt}/{max_attempts} - Enter password: ") if password == correct_password: print("Login successful! Welcome!") break else: remaining = max_attempts - attempt if remaining > 0: print(f"Incorrect password. {remaining} attempts remaining.") else: print("Account locked! Too many failed attempts.")
The break statement only exits the innermost loop. If you have nested loops, break will only exit the loop it's directly inside, not all loops.

3.2 Continue Statement

The continue statement skips the rest of the current iteration and moves to the next iteration of the loop. It's useful when you want to skip certain items but continue processing others. Unlike break, continue doesn't exit the loop.

# Skipping even numbers print("Odd numbers from 1 to 10:") for i in range(1, 11): if i % 2 == 0: continue # Skip even numbers print(i, end=" ") print("\n\nEven numbers from 1 to 10:") for i in range(1, 11): if i % 2 != 0: continue # Skip odd numbers print(i, end=" ")
Odd numbers from 1 to 10: 1 3 5 7 9 Even numbers from 1 to 10: 2 4 6 8 10
# Processing valid data only print("Processing student scores:") scores = [85, -5, 92, 78, 150, 88, 0, 100] valid_count = 0 invalid_count = 0 for score in scores: # Skip invalid scores if score < 0 or score > 100: print(f"Invalid score: {score} - skipping") invalid_count += 1 continue # Process valid scores valid_count += 1 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "D" print(f"Score: {score} - Grade: {grade}") print(f"\nSummary: {valid_count} valid, {invalid_count} invalid scores")
Processing student scores: Score: 85 - Grade: B Invalid score: -5 - skipping Score: 92 - Grade: A Score: 78 - Grade: C Invalid score: 150 - skipping Score: 88 - Grade: B Score: 0 - Grade: D Score: 100 - Grade: A Summary: 6 valid, 2 invalid scores
# Skipping specific items print("Printing fruits except banana:") fruits = ["apple", "banana", "cherry", "banana", "orange", "banana"] for fruit in fruits: if fruit == "banana": continue print(fruit)
Printing fruits except banana: apple cherry orange
Use continue when you want to skip some iterations but keep the loop running. Use break when you want to stop the loop entirely.

3.3 Pass Statement

The pass statement is a null operation that does nothing. It's used as a placeholder when you need syntactically correct code but don't want to execute anything yet. It's useful during development when you're planning code structure but haven't implemented the logic yet.

# Using pass as placeholder in loops print("Processing items:") for i in range(5): if i == 2: pass # TODO: Add special handling for item 2 later else: print(f"Processing item {i}") print("\nLoop completed!")
Processing items: Processing item 0 Processing item 1 Processing item 3 Processing item 4 Loop completed!
# Pass in different contexts # Empty function definition def future_function(): pass # Will implement this later # Empty class definition class MyFutureClass: pass # Will add methods later # Pass in conditional x = 10 if x > 5: pass # Do nothing for now else: print("x is 5 or less") print("Pass statement examples completed!")
Pass statement examples completed!
# Practical use of pass - selective processing numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("Processing numbers:") for num in numbers: if num % 3 == 0: pass # Skip multiples of 3 for now elif num % 2 == 0: print(f"{num} is even") else: print(f"{num} is odd")
Processing numbers: 1 is odd 2 is even 4 is even 5 is odd 7 is odd 8 is even 10 is even
Unlike break and continue, pass doesn't affect the flow of the program. It simply serves as a placeholder that allows your code to run without syntax errors. When you're ready, you can replace pass with actual code.
Comparison of Loop Control Statements:
  • break: Exits the loop completely
  • continue: Skips to the next iteration
  • pass: Does nothing, just a placeholder

Practical Examples

Let's look at some real-world examples that combine multiple control structures to solve common programming problems.

Example 1: Number Guessing Game

import random # Generate random number between 1 and 100 secret_number = random.randint(1, 100) attempts = 0 max_attempts = 7 print("="*50) print("Welcome to the Number Guessing Game!") print("="*50) print(f"I'm thinking of a number between 1 and 100.") print(f"You have {max_attempts} attempts to guess it.\n") while attempts < max_attempts: # Get user input guess = int(input(f"Attempt {attempts + 1}/{max_attempts} - Enter your guess: ")) attempts += 1 # Check the guess if guess == secret_number: print(f"\nšŸŽ‰ Congratulations! You guessed it in {attempts} attempts!") print(f"The number was {secret_number}") break elif guess < secret_number: print("šŸ“ˆ Too low! Try a higher number.") else: print("šŸ“‰ Too high! Try a lower number.") # Show remaining attempts remaining = max_attempts - attempts if remaining > 0: print(f"Attempts remaining: {remaining}\n") else: print(f"\nšŸ˜ž Game Over! You've used all {max_attempts} attempts.") print(f"The number was {secret_number}")

Example 2: Shopping Cart Calculator

# Shopping cart with discount calculation cart_items = { "Apple": 1.50, "Banana": 0.75, "Orange": 2.00, "Milk": 3.50, "Bread": 2.25 } print("="*50) print("SHOPPING CART") print("="*50) subtotal = 0 item_count = 0 # Display items and calculate subtotal for item, price in cart_items.items(): print(f"{item:15} ${price:.2f}") subtotal += price item_count += 1 print("-"*50) print(f"{'Subtotal':15} ${subtotal:.2f}") # Apply discounts based on conditions discount = 0 discount_reason = "" if subtotal > 20: discount = subtotal * 0.15 # 15% discount discount_reason = "15% discount (order > $20)" elif subtotal > 10: discount = subtotal * 0.10 # 10% discount discount_reason = "10% discount (order > $10)" elif item_count >= 5: discount = subtotal * 0.05 # 5% discount discount_reason = "5% discount (5+ items)" if discount > 0: print(f"{'Discount':15} -${discount:.2f} ({discount_reason})") # Calculate tax and total tax = (subtotal - discount) * 0.08 # 8% tax total = subtotal - discount + tax print(f"{'Tax (8%)':15} ${tax:.2f}") print("="*50) print(f"{'TOTAL':15} ${total:.2f}") print("="*50)

Example 3: Password Strength Checker

def check_password_strength(password): """Check password strength based on multiple criteria""" # Initialize counters length = len(password) has_upper = False has_lower = False has_digit = False has_special = False strength_score = 0 # Check each character for char in password: if char.isupper(): has_upper = True elif char.islower(): has_lower = True elif char.isdigit(): has_digit = True elif char in "!@#$%^&*()_+-=[]{}|;:,.<>?": has_special = True # Calculate strength score if length >= 8: strength_score += 1 if length >= 12: strength_score += 1 if has_upper: strength_score += 1 if has_lower: strength_score += 1 if has_digit: strength_score += 1 if has_special: strength_score += 1 # Determine strength level if strength_score <= 2: strength = "Weak" color = "šŸ”“" elif strength_score <= 4: strength = "Medium" color = "🟔" else: strength = "Strong" color = "🟢" # Display results print(f"\nPassword: {password}") print(f"Length: {length} characters") print(f"Has uppercase: {'āœ“' if has_upper else 'āœ—'}") print(f"Has lowercase: {'āœ“' if has_lower else 'āœ—'}") print(f"Has digits: {'āœ“' if has_digit else 'āœ—'}") print(f"Has special characters: {'āœ“' if has_special else 'āœ—'}") print(f"Strength: {color} {strength} (Score: {strength_score}/6)") # Test different passwords passwords = ["pass", "Password", "Pass123", "P@ssw0rd!", "MyP@ssw0rd2024!"] for pwd in passwords: check_password_strength(pwd) print("-"*50)

Example 4: Student Grade Statistics

# Calculate statistics for student grades students_grades = { "Alice": [85, 92, 78, 90, 88], "Bob": [70, 75, 72, 68, 71], "Charlie": [95, 98, 92, 96, 94], "Diana": [60, 65, 58, 62, 64], "Eve": [88, 85, 90, 87, 86] } print("="*60) print("STUDENT GRADE REPORT") print("="*60) # Process each student for student, grades in students_grades.items(): print(f"\n{student}:") print(f"Grades: {grades}") # Calculate statistics total = 0 highest = grades[0] lowest = grades[0] for grade in grades: total += grade if grade > highest: highest = grade if grade < lowest: lowest = grade average = total / len(grades) # Determine letter grade if average >= 90: letter_grade = "A" elif average >= 80: letter_grade = "B" elif average >= 70: letter_grade = "C" elif average >= 60: letter_grade = "D" else: letter_grade = "F" # Display results print(f"Average: {average:.2f}") print(f"Highest: {highest}") print(f"Lowest: {lowest}") print(f"Letter Grade: {letter_grade}") # Add performance message if average >= 90: print("Performance: Excellent! 🌟") elif average >= 80: print("Performance: Very Good! šŸ‘") elif average >= 70: print("Performance: Good šŸ‘Œ") elif average >= 60: print("Performance: Needs Improvement šŸ“š") else: print("Performance: Requires Attention āš ļø") print("\n" + "="*60)

Summary

Key Takeaways:

1. Conditional Statements:
  • Use if-else for simple binary decisions
  • Use if-elif-else for multiple conditions
  • Use nested if for hierarchical conditions
  • Use ternary operator for simple conditional assignments
2. Loops:
  • Use for loops when you know how many iterations you need
  • Use while loops when iterations depend on a condition
  • Use enumerate() when you need both index and value
  • Use zip() to iterate over multiple sequences together
3. Loop Control:
  • Use break to exit a loop early
  • Use continue to skip the current iteration
  • Use pass as a placeholder for future code
Best Practices:
  • Always ensure loops have a termination condition
  • Use meaningful variable names in loops
  • Keep indentation consistent (4 spaces is standard)
  • Choose the right control structure for your problem
  • Comment complex conditional logic
  • Avoid deeply nested loops when possible